"""
智能体角色定义模块

定义系统中所有智能体的角色、级别和权限。
"""

from enum import Enum
from typing import List, Dict, Any
from dataclasses import dataclass


class AgentLevel(Enum):
    """智能体层级"""
    STRATEGIC = "strategic"      # 战略决策层
    MANAGEMENT = "management"    # 管理执行层  
    OPERATIONAL = "operational"  # 专业操作层


class AgentRole(Enum):
    """智能体角色枚举"""
    
    # 战略决策层
    CIO = "cio"                                    # 首席投资官
    INVESTMENT_COMMITTEE = "investment_committee"   # 投资决策委员会
    BOARD_REPRESENTATIVE = "board_representative"   # 董事会代表
    
    # 管理执行层
    RESEARCH_DIRECTOR = "research_director"         # 研究总监
    TRADING_DIRECTOR = "trading_director"           # 交易总监
    RISK_DIRECTOR = "risk_director"                 # 风控总监
    TECH_DIRECTOR = "tech_director"                 # 技术总监
    COMPLIANCE_DIRECTOR = "compliance_director"     # 合规总监
    
    # 专业操作层 - 研究团队
    MACRO_RESEARCHER = "macro_researcher"           # 宏观研究员
    INDUSTRY_RESEARCHER = "industry_researcher"     # 行业研究员
    COMPANY_RESEARCHER = "company_researcher"       # 公司研究员
    QUANT_RESEARCHER = "quant_researcher"           # 量化研究员
    ESG_RESEARCHER = "esg_researcher"               # ESG研究员
    
    # 专业操作层 - 量化团队
    FACTOR_ENGINEER = "factor_engineer"             # 因子挖掘
    STRATEGY_DEVELOPER = "strategy_developer"       # 策略开发
    BACKTEST_ANALYST = "backtest_analyst"           # 回测验证
    RISK_MODELER = "risk_modeler"                   # 风险建模
    PERFORMANCE_ANALYST = "performance_analyst"     # 绩效归因
    
    # 专业操作层 - 交易团队
    ALGO_TRADER = "algo_trader"                     # 算法交易
    ALGORITHMIC_TRADER = "algorithmic_trader"       # 算法交易员
    EXECUTION_TRADER = "execution_trader"           # 执行交易
    MARKET_MAKER = "market_maker"                   # 做市交易
    
    # 专业操作层 - 分析团队
    MARKET_ANALYST = "market_analyst"               # 市场分析师
    QUANTITATIVE_ANALYST = "quantitative_analyst"   # 量化分析师
    FUNDAMENTAL_ANALYST = "fundamental_analyst"     # 基本面分析师
    TECHNICAL_ANALYST = "technical_analyst"         # 技术分析师
    MACRO_ANALYST = "macro_analyst"                 # 宏观分析师
    CREDIT_ANALYST = "credit_analyst"               # 信用分析师
    RISK_ANALYST = "risk_analyst"                   # 风险分析师
    
    # 专业操作层 - 管理团队
    PORTFOLIO_MANAGER = "portfolio_manager"         # 投资组合经理
    INVESTMENT_DIRECTOR = "investment_director"     # 投资总监
    OPERATIONS_DIRECTOR = "operations_director"     # 运营总监
    
    # 专业操作层 - 支持团队
    DATA_ENGINEER = "data_engineer"                 # 数据工程师
    SYSTEM_ADMIN = "system_admin"                   # 系统运维
    COMPLIANCE_OFFICER = "compliance_officer"       # 合规监察
    CLIENT_SERVICE = "client_service"               # 客户服务
    CLIENT_RELATIONS_MANAGER = "client_relations_manager"  # 客户关系经理


@dataclass
class AgentCapability:
    """智能体能力定义"""
    name: str
    description: str
    required_skills: List[str]
    tools: List[str]
    permissions: List[str]


@dataclass
class AgentRoleConfig:
    """智能体角色配置"""
    role: AgentRole
    level: AgentLevel
    name_zh: str
    name_en: str
    description: str
    capabilities: List[AgentCapability]
    reporting_to: List[AgentRole]
    manages: List[AgentRole]
    collaborates_with: List[AgentRole]
    priority: int  # 优先级，数字越小优先级越高


# 智能体角色配置映射
AGENT_ROLE_CONFIGS: Dict[AgentRole, AgentRoleConfig] = {
    
    # 战略决策层配置
    AgentRole.CIO: AgentRoleConfig(
        role=AgentRole.CIO,
        level=AgentLevel.STRATEGIC,
        name_zh="首席投资官",
        name_en="Chief Investment Officer",
        description="负责整体投资策略制定和重大投资决策",
        capabilities=[
            AgentCapability(
                name="投资策略制定",
                description="制定公司整体投资策略和方向",
                required_skills=["战略规划", "市场分析", "风险管理"],
                tools=["策略分析工具", "市场数据平台", "风险评估系统"],
                permissions=["策略审批", "资产配置决策", "风险限额设定"]
            )
        ],
        reporting_to=[],
        manages=[AgentRole.RESEARCH_DIRECTOR, AgentRole.TRADING_DIRECTOR, AgentRole.RISK_DIRECTOR],
        collaborates_with=[AgentRole.INVESTMENT_COMMITTEE, AgentRole.BOARD_REPRESENTATIVE],
        priority=1
    ),
    
    AgentRole.INVESTMENT_COMMITTEE: AgentRoleConfig(
        role=AgentRole.INVESTMENT_COMMITTEE,
        level=AgentLevel.STRATEGIC,
        name_zh="投资决策委员会",
        name_en="Investment Committee",
        description="集体决策重大投资事项和策略调整",
        capabilities=[
            AgentCapability(
                name="集体决策",
                description="重大投资决策的集体讨论和表决",
                required_skills=["投资分析", "风险评估", "决策协调"],
                tools=["决策支持系统", "投票系统", "会议管理工具"],
                permissions=["重大投资审批", "策略变更决策", "风险政策制定"]
            )
        ],
        reporting_to=[AgentRole.BOARD_REPRESENTATIVE],
        manages=[],
        collaborates_with=[AgentRole.CIO],
        priority=2
    ),
    
    # 管理执行层配置
    AgentRole.RESEARCH_DIRECTOR: AgentRoleConfig(
        role=AgentRole.RESEARCH_DIRECTOR,
        level=AgentLevel.MANAGEMENT,
        name_zh="研究总监",
        name_en="Research Director",
        description="统筹管理研究团队，制定研究方向和标准",
        capabilities=[
            AgentCapability(
                name="研究管理",
                description="管理和协调各类研究活动",
                required_skills=["研究方法论", "团队管理", "质量控制"],
                tools=["研究管理平台", "质量评估工具", "团队协作系统"],
                permissions=["研究方向制定", "研究质量审核", "团队资源分配"]
            )
        ],
        reporting_to=[AgentRole.CIO],
        manages=[
            AgentRole.MACRO_RESEARCHER, AgentRole.INDUSTRY_RESEARCHER,
            AgentRole.COMPANY_RESEARCHER, AgentRole.QUANT_RESEARCHER, AgentRole.ESG_RESEARCHER
        ],
        collaborates_with=[AgentRole.TRADING_DIRECTOR, AgentRole.RISK_DIRECTOR],
        priority=10
    ),
    
    # 专业操作层配置示例
    AgentRole.MACRO_RESEARCHER: AgentRoleConfig(
        role=AgentRole.MACRO_RESEARCHER,
        level=AgentLevel.OPERATIONAL,
        name_zh="宏观研究员",
        name_en="Macro Researcher",
        description="负责宏观经济分析和政策研究",
        capabilities=[
            AgentCapability(
                name="宏观分析",
                description="分析宏观经济趋势和政策影响",
                required_skills=["宏观经济学", "政策分析", "数据分析"],
                tools=["经济数据库", "政策追踪系统", "预测模型"],
                permissions=["宏观报告发布", "经济数据访问", "政策解读"]
            )
        ],
        reporting_to=[AgentRole.RESEARCH_DIRECTOR],
        manages=[],
        collaborates_with=[
            AgentRole.INDUSTRY_RESEARCHER, AgentRole.QUANT_RESEARCHER,
            AgentRole.RISK_MODELER
        ],
        priority=100
    ),
}


def get_agent_config(role: AgentRole) -> AgentRoleConfig:
    """获取智能体角色配置"""
    return AGENT_ROLE_CONFIGS.get(role)


def get_agents_by_level(level: AgentLevel) -> List[AgentRole]:
    """根据层级获取智能体角色列表"""
    return [
        role for role, config in AGENT_ROLE_CONFIGS.items()
        if config.level == level
    ]


def get_reporting_chain(role: AgentRole) -> List[AgentRole]:
    """获取汇报链"""
    config = get_agent_config(role)
    if not config or not config.reporting_to:
        return []
    
    chain = []
    for manager in config.reporting_to:
        chain.append(manager)
        chain.extend(get_reporting_chain(manager))
    
    return chain


def get_collaboration_network(role: AgentRole) -> Dict[str, List[AgentRole]]:
    """获取协作网络"""
    config = get_agent_config(role)
    if not config:
        return {}
    
    return {
        "manages": config.manages,
        "reports_to": config.reporting_to,
        "collaborates_with": config.collaborates_with
    }